package com.ustcinfo.ishare.bdp.hbase;


import java.io.IOException;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Admin;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.apache.hadoop.hbase.client.Get;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.Table;
import org.apache.hadoop.hbase.client.replication.ReplicationAdmin;
import org.apache.hadoop.hbase.util.Bytes;

public class Hbase_reader {

	//集群配置对象
	private static Configuration conf = null;

	//配置连接对象
	private static Connection connection = null;

	/*hbase集群管理对象*/
	private static Admin admin = null;

	/*hbase replication管理对象*/
	private static ReplicationAdmin replicationAdmin = null;

	/**
	 * 初始化
	 */
	static {
		conf = HBaseConfiguration.create();
		conf.set("hbase.master", "hdfs://192.168.142.100:60000");
		conf.set("hbase.zookeeper.property.clientPort", "2181");
		conf.set("hbase.zookeeper.quorum", "192.168.142.100,192.168.142.101,192.168.142.102");
		conf.set("hbase.rootdir", "hdfs://192.168.142.100:9000/hbase");
		try {
			connection = ConnectionFactory.createConnection(conf);
			admin = connection.getAdmin();
			replicationAdmin = new ReplicationAdmin(conf);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 单表查询
	 * @param name
	 * @param rowKey
	 * @return
	 */
	public static Result get(String name, String rowKey) {
		TableName tableName = TableName.valueOf(name);
		Result result = null;
		try (Table table = connection.getTable(tableName)) {
			Get get = new Get(rowKey.getBytes());
			result = table.get(get);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return result;
	}

	public static void selectRowKey(String tablename, String rowKey) throws IOException{
		Table table = connection.getTable(TableName.valueOf(tablename));

		Get g = new Get(Bytes.toBytes(rowKey));
		Result result = table.get(g);

		byte [] value = result.getValue(Bytes.toBytes("info"), Bytes.toBytes("name"));
		byte[] value1 = result.getValue(Bytes.toBytes("info"), Bytes.toBytes("age"));

		table.close();
		System.out.println(result.toString());
		System.out.println(Bytes.toString(value));
		System.out.println(Bytes.toString(value1));
	}

	public static void main(String[] args) {
		try {
			selectRowKey("test","001");
			
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
